import * as api from '../../services/example';
import { Toast } from 'antd-mobile';
import { routerRedux } from 'dva/router';

export default {
  namespace: 'detail',
  state: {
    data: [],
    index: 0,
    flow: [],
    flowUser: [],
    flowIndex: 0,
    selectIndex: 0,
    tabs: [
      { title: '主表单', sub: '1' },
      { title: '正文/附件', sub: '2' },
      { title: '历史意见', sub: '3' },
      { title: '流程跟踪', sub: '4' },
      { title: '待阅记录', sub: '4' },
    ],
    visible: false,
    modalVisible: false,
    process: 'none',
    loading: false,
    message: '',
    label: '发',
    disabled: true,
    personList: [],
    item: {},
    selectList: [],
    inx: -1,
  },
  reducers: {
    showView(state, { payload }) {
      const { flow, user, disabled } = payload || state;
      const { personList } = state;
      const users = user && user.attinfo;
      users &&
        users.forEach((item) => {
          if (item.person !== '') {
            if (personList.indexOf(item.person) === -1) {
              personList.push(item.person);
            }
          }
        });
      return {
        ...state,
        modalVisible: true,
        flowUser: (user && user.attinfo) || state.flowUser,
        flow,
        loading: false,
        disabled,
        personList,
      };
    },
    selectItems(state, { payload }) {
      const { item } = payload;
      const { personList } = state;
      const name = item.person || item.enName;
      const index = personList.indexOf(name);
      if (index > -1) {
        personList.splice(index, 1);
      } else {
        personList.push(name);
      }
      return {
        ...state,
        personList,
      };
    },
    hide(state, { payload }) {
      const { close } = payload;
      const { personList } = state;
      return {
        ...state,
        modalVisible: false,
        flowIndex: 0,
        personList: close ? [] : personList,
      };
    },
   success(state, { payload }) {
     return {
       ...state,
       modalVisible: false,
       personList: [],
       message: '',
       label: '发',
     };
   },
    process(state, { payload }) {
      const { parocess, flowIndex } = payload;
      return {
        ...state,
        process: parocess === 'none' ? 'block' : 'none',
        flowIndex,
      };
    },
    querySuccess(state, { payload }) {
      const { data, index, item } = payload;
      return {
        ...state,
        data,
        index,
        item,
        loading: false,
        search: item,
      };
    },
    loading(state, { payload }) {
      const { flag } = payload;
      return {
        ...state,
        loading: flag,
      };
    },
    select(state, { payload }) {
      const { selectIndex } = payload;
      let str;
      if (selectIndex === 0) {
        str = '发';
      } else if (selectIndex === 1) {
        str = '已阅';
      } else if (selectIndex === 2) {
        str = '同意';
      } else {
        str = '拟同意';
      }
      return {
        ...state,
        ...payload,
        label: str,
      };
    },
    input(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    enable(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    queryUser(state, { payload }) {
      const { user } = payload || state;
      const list = [];
      user.attinfo &&
        user.attinfo.length > 0 &&
        user.attinfo.forEach((item) => {
          if (item.person.length > 0) list.push(item.person);
        });
      return {
        ...state,
        personList: list,
        flowUser: (user && user.attinfo) || state.flowUser,
      };
    },
    goContacts(state, { payload }) {
      const { personList } = state;
      return {
        ...state,
        personList,
      };
    },
    showMsg(state, { payload }) {
      const { inx } = payload;
      return {
        ...state,
        inx,
      };
    },
    backView (state, {payload}) {
      const {selectP} = payload
      let {personList} = state
      const arr = personList.filter(item => {
       return selectP.indexOf(item) === -1
      })
      return {
        ...state,
        personList: arr
      }
    }
  },
  effects: {
    *query({ payload = {} }, { call, put, select }) {
      // 执行异步方法
      yield put({ type: 'loading', payload: { flag: true } });
      const { item, index } = payload;
      let data;
      const path = item.dbpath
        .split('/')
        .splice(1)
        .join('/');
      if (index === 1) {
        data = yield call(api.queryformDocInfo, {
          serverName: '',
          dbPath: path,
          id: item.fldUnid,
        });
      } else if (index === 2) {
        data = yield call(api.queryformHisInfo, {
          serverName: '',
          dbPath: path,
          id: item.fldUnid,
        });
      } else if (index === 3) {
        data = yield call(api.queryformFlowHisInfo, {
          serverName: '',
          dbPath: path,
          id: item.fldUnid,
        });
      } else if (index === 4) {
        data = yield call(api.queryformCyHisInfo, {
          serverName: '',
          dbPath: path,
          id: item.fldUnid,
        });
      } else {
        data = yield call(api.queryFormDetail, {
          serverName: '',
          dbPath: path,
          id: item.fldUnid,
        });
      } 
      if (data.data) {
        let result;
        if (index === 1) {
          const { flag, fileData } = data.data;
          if (parseInt(flag) === 0) {
            result = [];
          } else {
            result = fileData;
          }
        } else if (index === 2) {
          result = data.data.hisYj;
        } else if (index === 3) {
          result = data.data;
        } else if (index === 4) {
          const res = data.data;
          const { flag, fldyzvalue } = res;
          if (parseInt(flag) === 0) {
            result = { fldyzvalue: [] };
          } else {
            result = { fldyzvalue };
          }
        } else {
          result = data.data.detailAll;
        }
        yield put({
          type: 'querySuccess',
          payload: { data: result, index, item },
        });
        yield put({ type: 'loading', payload: { flag: false } });
      }
    },
    *show({ payload = {} }, { call, put, select }) {
      yield put({ type: 'loading', payload: { flag: true } });
      const st = yield select(state => state.detail);
      const { item } = st;
      const path = item.dbpath
        .split('/')
        .splice(1)
        .join('/');
      // 查询环节数据
      const flow = yield call(api.queryflowForName, {
        requestId: item.fldUnid,
        unid: item.fldUnid,
        dbPath: path,
        userCode: sessionStorage.getItem('usercode'),
        opin: '',
      });
      
      const flowResult = flow.data;
      yield put({
        type: 'submit',
        payload: { flow: flowResult, disabled: false },
      });

      // const { hfldNextflownum } = flowResult;
      // const flowNum = hfldNextflownum[0];
      // // 验证环节
      // const data = yield call(api.validateFlow, {
      //   requestId: item.fldUnid,
      //   unid: item.fldUnid,
      //   dbPath: path,
      //   curuser: sessionStorage.getItem('usercode'),
      //   extension: '1',
      //   opin: `,${flowNum}`,
      // });
     
      // const { flag, msg } = data.data;
      // if (parseInt(flag) === 1) {
      //   yield put({
      //     type: 'sumbit',
      //     payload: { flow: flowResult, disabled: false },
      //   });
      // } else {
      //   Toast.fail(msg);
      // }
      yield put({ type: 'loading', payload: { flag: false } });
    },

    *submit({ payload = {} }, { call, put, select }) {
      let { flow } = payload;
      const { requestId, unid, dataPath } = flow;
      yield put({ type: 'loading', payload: { flag: true } });  
      const result = yield call(api.submit, {
        requestId,
        unid,
        dbPath: dataPath,
        curuser: sessionStorage.getItem('usercode'),
        extension: '1',
        opin: `1`,
      });
      const res = yield put({ type: 'loading', payload: { flag: false } });
      const { flag, msg } = result.data;
      //alert(flag)//1
      if (parseInt(flag) === 1) {
        Toast.success('提交成功', 1);
        yield put({ type: 'success' });
        yield put(routerRedux.push('/index'));
      } else {
        Toast.fail(msg);
      }
    },
    *validate({ payload = {} }, { call, put, select }) {
      yield put({ type: 'loading', payload: { flag: true } });
      const detail = yield select(state => state.detail);
      const { flow, flowIndex } = detail;
      const { requestId, unid, dataPath } = flow;
      const { hfldNextflownum } = flow;
      const flowNum = hfldNextflownum[flowIndex];
      const user = yield call(api.queryflowPerson, {
        requestId,
        unid,
        dbPath: dataPath,
        curuser: sessionStorage.getItem('usercode'),
        extension: 1,
        opin: flowNum,
      });
      const userResult = user.data;

      // 验证环节
      const data = yield call(api.validateFlow, {
        requestId,
        unid,
        dbPath: dataPath,
        curuser: sessionStorage.getItem('usercode'),
        extension: '1',
        opin: `,${flowNum}`,
      });
      const { flag, msg } = data.data;
      if (parseInt(flag) === 1) {
        yield put({ type: 'enable', payload: { disable: false } });
      } else {
        Toast.fail(msg);
        yield put({ type: 'enable', payload: { disable: true } });
      }
      yield put({ type: 'loading', payload: { flag: false } });
      yield put({ type: 'queryUser', payload: { user: userResult } });
      yield put({ type: 'contacts/init', payload: { init: true, clear: true } });
    },
    *selectItem({ payload = {} }, { call, put, select }) {
      const { item } = payload;
      const { personList } = yield select(_ => _.detail);
      yield put({ type: 'contacts/filterPerson', payload: { item, personList } });
      yield put({ type: 'selectItems', payload: { item } });
    },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen((location) => {
        if (location.query) {
          const { item } = location.query;
          dispatch({
            type: 'query',
            payload: { item },
          });
        }
      });
    },
  },
};
